<template>
	<div v-loading="loading" element-loading-text="正在加载产线数据">
		<el-row :gutter="20" justify="space-around">
			<el-col :span="14" :xs="24">
				<div class="tree">
					<div style="margin-bottom: 10px">
						<el-button icon="el-icon-Bottom" size="small" type="primary" @click="expandAll">展开全部</el-button>
						<el-button icon="el-icon-Top" size="small" type="primary" @click="collapseAll">收起全部</el-button>
					</div>
					<el-tree
							ref="treeRef"
							:data="productionLineDataInner!.treeData"
							:default-expand-all="true"
							:expand-on-click-node="false"
							:props="treeProps"
					>
						<template v-slot="{node, data}">
				      <span class="custom-tree-node">
					      <span>
						      <el-link :underline="false" type="primary" @click="showItemDetail(data.itemId)">{{ data.itemName }}</el-link>
				          <span>{{ data.quantityPerMinute ? '，' + data.quantityPerMinute + '/min' : '' }}</span>
				          <span v-if="data.byProductList && data.byProductList.length > 0">（副产物：<span
						          v-for="byProduct in data.byProductList"
				          ><el-link :underline="false" style="" type="warning" @click="showItemDetail(byProduct.itemId)">{{
						          byProduct.itemName
					          }}</el-link>{{ '，' + byProduct.quantityPerMinute + '/min' }}<span
						          v-if="data.byProductList.indexOf(byProduct) !== data.byProductList.length - 1"
				          >；</span></span>）</span>
				        </span>
				        <span>
				          <span v-if="data.buildingVo">
					          <el-link :underline="false" type="primary" @click="showBuildingDetail(data.buildingVo.buildingId)">{{
							          data.buildingVo.buildingName
						          }}</el-link>
				            <span>{{ '*' + data.buildingVo.count + '（' + data.buildingVo.countExact + '）' }}</span>
				          </span>
				          <span v-else-if="data.handmadeBuildingVoList && data.handmadeBuildingVoList.length > 0">
				            手搓（<span v-for="building in data.handmadeBuildingVoList">
					            <el-link :underline="false" type="primary"
					                     @click="showBuildingDetail(building.buildingId)">{{ building.buildingName }}</el-link>
				              <span
						              v-if="data.handmadeBuildingVoList.indexOf(building) < data.handmadeBuildingVoList.length - 1">，</span>
				            </span>）
				          </span>
				        </span>
				      </span>
						</template>
					</el-tree>
				</div>
			</el-col>
			<el-col :span="1"></el-col>
			<el-col :span="9" :xs="24">
				<div class="statistics">
					<cus-form-title :show-divider="false" :show-icon="false" label="数据统计"></cus-form-title>
					<el-collapse v-model="activeNames">
						<el-collapse-item v-if="productionLineDataInner!.statistics.basicMaterialList.length > 0" name="material" title="原料">
							<!-- 原料 -->
							<el-descriptions :column="1" border>
								<el-descriptions-item v-for="item in productionLineDataInner!.statistics.basicMaterialList" :key="item.itemId" label-align="center">
									<template #label>
										{{ item.itemName }}
									</template>
									<div class="cus-center">
										{{ item.quantityPerMinute }}/min
										<el-image :src="getImage(item.image!)" fit="contain"
										          style="width: 50px; height: 50px;cursor: pointer;margin-left: 10px"
										          @click="showItemDetail(item.itemId!)"></el-image>
									</div>
								</el-descriptions-item>
							</el-descriptions>
						</el-collapse-item>
						<el-collapse-item v-if="productionLineDataInner!.statistics.byProductList.length > 0" name="byProduct" title="副产物">
							<!-- 副产物 -->
							<el-descriptions :column="1" border>
								<el-descriptions-item v-for="item in productionLineDataInner!.statistics.byProductList" :key="item.itemId" label-align="center">
									<template #label>
										{{ item.itemName }}
									</template>
									<div class="cus-center">
										{{ item.quantityPerMinute }}/min
										<el-image :src="getImage(item.image!)" fit="contain"
										          style="width: 50px; height: 50px;cursor: pointer;margin-left: 10px"
										          @click="showItemDetail(item.itemId!)"></el-image>
									</div>
								</el-descriptions-item>
							</el-descriptions>
						</el-collapse-item>
						<el-collapse-item v-if="productionLineDataInner!.statistics.productionLineBuildingList.length > 0" name="productionLineBuilding" title="建筑">
							<!-- 建筑 -->
							<el-descriptions :column="1" border>
								<el-descriptions-item v-for="building in productionLineDataInner!.statistics.productionLineBuildingList" :key="building.buildingId"
								                      label-align="center">
									<template #label>
										{{ building.buildingName }}
									</template>
									<div class="cus-center">
										{{ building.count || 1 }}<span v-if="building.count && building.count !== building.countExact">（{{ building.countExact }}）</span>&nbsp;
										<el-image :src="getImage(building.image!)" fit="contain" style="width: 50px; height: 50px;cursor: pointer;margin-left: 10px"
										          @click="showBuildingDetail(building.buildingId!)"></el-image>
									</div>
								</el-descriptions-item>
							</el-descriptions>
						</el-collapse-item>
						<el-collapse-item name="power" title="电力">
							<!-- 电力 -->
							<el-descriptions :column="1" border>
								<el-descriptions-item label-align="center">
									<template #label>
										总耗电量
									</template>
									<div class="cus-center">
										{{ productionLineDataInner!.statistics.totalPower }} MW
									</div>
								</el-descriptions-item>
							</el-descriptions>
						</el-collapse-item>
					</el-collapse>
				</div>
			</el-col>
		</el-row>

		<!-- 对话框（物品详情） -->
		<cus-item-dialog v-model:visible="dialogVisible.item" :item-id="itemIdDisplayed"/>

		<!-- 对话框（建筑详情） -->
		<cus-building-dialog v-model:visible="dialogVisible.building" :building-id="buildingIdDisplayed"/>
	</div>

</template>

<script lang="ts" name="ProductionLineDetail" setup>
import {elTreeIterator, getImage} from '@/utils/commonUtil'
import {ElTree} from 'element-plus'
import CusFormTitle from '@/components/cus-form-title.vue'
import type Node from 'element-plus/es/components/tree/src/model/node'
import {reactive, ref} from 'vue'
import CusBuildingDialog from '@/components/cus-building-dialog.vue'
import CusItemDialog from '@/components/cus-item-dialog.vue'
import {useRoute} from 'vue-router'
import {getUserProductionByIdApi} from '@/api/gameTool/productionLine.api'

const route = useRoute()

interface Props {
	productionLineData?: ProductionLineData
}

const treeRef = ref()

const props = withDefaults(defineProps<Props>(), {
	productionLineData: undefined
})

const loading = ref(false)

const productionLineDataInner = reactive<ProductionLineData>({
	treeData: [],
	statistics: {
		basicMaterialList: [],
		byProductList: [],
		productionLineBuildingList: [],
		totalPower: 0
	}
})

const treeProps = reactive({
	label: 'name',
	children: 'children',
	isLeaf: 'leaf',
	disabled: 'disabled'
})
const activeNames = ref(['material', 'byProduct', 'productionLineBuilding', 'power'])
const dialogVisible = reactive({
	item: false,
	building: false
})
const itemIdDisplayed = ref<number>()
const buildingIdDisplayed = ref<number>()

const expandAll = () => {
	elTreeIterator(treeRef.value!, (node: Node) => {
		if (node.childNodes && node.childNodes.length > 0) {
			node.expanded = true
		}
	})
}

const collapseAll = () => {
	elTreeIterator(treeRef.value!, (node: Node) => {
		if (node.childNodes && node.childNodes.length > 0) {
			node.expanded = false
		}
	})
}

const showItemDetail = (itemId: number) => {
	itemIdDisplayed.value = itemId
	dialogVisible.item = true
}

const showBuildingDetail = (buildingId: number) => {
	buildingIdDisplayed.value = buildingId
	dialogVisible.building = true
}

// 优先使用props中的产线数据，如果没有则根据路由参数中的生产线id查询产线数据
loading.value = true
if (props.productionLineData) {
	Object.assign(productionLineDataInner, props.productionLineData)
	loading.value = false
} else {
	const lineId = route.path.split('/').pop()
	if (!lineId) {
		throw Error('无法从路由中获取产线id')
	}
	const lineIdNumber = Number(lineId)
	if (lineIdNumber <= 0 || !Number.isSafeInteger(lineIdNumber)) {
		throw Error('产线id必须为正整数')
	}
	getUserProductionByIdApi(lineIdNumber).then(response => {
		const userProduction = response.data
		const parse = JSON.parse(userProduction.data!)
		productionLineDataInner.treeData = parse.treeData
		productionLineDataInner.statistics = parse.statistics
	}).finally(() => {
		loading.value = false
	})
}

</script>

<style lang="scss" scoped>
.tree {
	border-radius: var(--el-border-radius-base);
	box-shadow: var(--cus-box-shadow);
	padding: 10px;
}

.statistics {
	border-radius: var(--el-border-radius-base);
	box-shadow: var(--cus-box-shadow);
	padding: 10px;
}

.custom-tree-node {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: space-between;
	font-size: var(--el-font-size-base);
	padding-right: 8px;
}
</style>
